package com.bzy.common.util.local;

import com.alibaba.fastjson.JSON;
import com.bzy.common.bean.Result;
import com.bzy.common.bean.ResultCode;
import com.bzy.common.exception.LogicException;
import com.bzy.common.exception.SpringValidException;
import com.bzy.common.exception.SqlException;
import com.bzy.common.exception.ValidateException;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;


public class ExceptionUtil {

	public static String getExceptionContent(Throwable e) {
		Writer result = new StringWriter();
		PrintWriter printWriter = new PrintWriter(result);
		e.printStackTrace(printWriter);
		return result.toString();
	}

	public static Result resolveException(Throwable e) {
		Result result = new Result();
		result.setSuccess(false);

		if (e instanceof SpringValidException) {
			List<String> errors = ((SpringValidException) e).getErrorMessages();
			result.setMessage(JSON.toJSONString(errors));
			result.setData(e.getMessage());
			result.setCode(ResultCode.VALIDATE_ERROR);
		} else if (e instanceof SqlException) {
			result.setMessage(e.getMessage());
			result.setCode(ResultCode.DAO_ERROR);
		} else if (e instanceof LogicException) {
			result.setMessage(e.getMessage());
			result.setCode(ResultCode.SERVICE_ERROR);
		} else if (e instanceof ValidateException){
			result.setMessage(e.getMessage());
			result.setCode(ResultCode.VALIDATE_ERROR);
		} else {
			result.setCode(ResultCode.ERROR);
			result.setMessage("服务异常，请重试！");
		}

		return result;
	}

}
